package com.ergwang.filter;

import com.ergwang.Model.Admin;
import com.ergwang.Model.Result;
import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Preconditions;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Creat by ergWang
 * Date: 2020/5/28
 * Time: 10:54
 */
@WebFilter("/api/admin/*")
public class AdminFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 将*改为了页面系统所在的域
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8085");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        String requestURI = request.getRequestURI();
        // 1,需要拦截那些请求
        // 2，针对需要拦截的，判断有无session数据
        // 3，如果没有，就拦截
        if (auth(requestURI)){
            Admin admin = (Admin) request.getSession().getAttribute("admin");
            if (admin == null){
                response.getWriter().println(new Gson().toJson(Result.error("当前接口仅登陆后可以访问！")));
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * 当前请求的uri是否需要权限
     * @param requestURI
     * @return
     */
    private boolean auth(String requestURI) {
        if ("/api/admin/admin/login".equals(requestURI) ||
            "/api/admin/admin/logoutAdmin".equals(requestURI)){
            return false;
        }
        return true;
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
